<!-- views/procurement/components/ContractManagement.vue -->
<template>
  <el-card class="contract-management-card" shadow="never">
    <template #header>
      <div class="card-header">
        <span>合同管理</span>
        <el-button type="primary" @click="showCreateDialog">新增合同</el-button>
      </div>
    </template>
    
    <!-- 筛选条件 -->
    <el-form :model="filterParams" :inline="true" class="filter-form">
      <el-form-item label="供应商">
        <el-select v-model="filterParams.supplierId" placeholder="请选择供应商" clearable class="form-item-width">
          <el-option
            v-for="supplier in suppliers"
            :key="supplier.id"
            :label="supplier.name"
            :value="supplier.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="filterParams.status" placeholder="请选择状态" clearable class="form-item-width">
          <el-option label="生效中" value="active" />
          <el-option label="已过期" value="expired" />
          <el-option label="已终止" value="terminated" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="loadContracts">查询</el-button>
        <el-button @click="resetFilter">重置</el-button>
      </el-form-item>
    </el-form>
    
    <!-- 合同列表 -->
    <AdvancedTable
      :data="contracts"
      :columns="contractColumns"
      :loading="loading"
      :pagination="paginationConfig"
      row-key="id"
      show-toolbar
      show-refresh
      show-pagination
      @refresh="loadContracts"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <template #contractType="{ row }">
        <el-tag v-if="row.contractType === 'purchase'">采购合同</el-tag>
        <el-tag v-else-if="row.contractType === 'service'">服务合同</el-tag>
        <el-tag v-else>其他合同</el-tag>
      </template>
      
      <template #status="{ row }">
        <el-tag v-if="row.status === 'active'" type="success">生效中</el-tag>
        <el-tag v-else-if="row.status === 'expired'" type="warning">已过期</el-tag>
        <el-tag v-else type="danger">已终止</el-tag>
      </template>
      
      <template #amount="{ row }">
        ¥{{ row.amount.toLocaleString() }}
      </template>
      
      <template #actions="{ row }">
        <el-button size="small" @click="viewContract(row)">查看</el-button>
        <el-button size="small" @click="editContract(row)">编辑</el-button>
        <el-button size="small" type="danger" @click="deleteContract(row)">删除</el-button>
      </template>
    </AdvancedTable>
  </el-card>
  
  <!-- 合同对话框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="editingContract ? '编辑合同' : '新增合同'"
    width="600px"
  >
    <el-form
      :model="contractForm"
      :rules="contractRules"
      ref="contractFormRef"
      label-width="100px"
    >
      <el-form-item label="合同编号" prop="contractNumber">
        <el-input v-model="contractForm.contractNumber" placeholder="请输入合同编号" />
      </el-form-item>
      
      <el-form-item label="供应商" prop="supplierId">
        <el-select v-model="contractForm.supplierId" placeholder="请选择供应商" class="form-item-width">
          <el-option
            v-for="supplier in suppliers"
            :key="supplier.id"
            :label="supplier.name"
            :value="supplier.id"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="合同名称" prop="contractName">
        <el-input v-model="contractForm.contractName" placeholder="请输入合同名称" />
      </el-form-item>
      
      <el-form-item label="合同类型" prop="contractType">
        <el-select v-model="contractForm.contractType" placeholder="请选择合同类型" class="form-item-width">
          <el-option label="采购合同" value="purchase" />
          <el-option label="服务合同" value="service" />
          <el-option label="其他合同" value="other" />
        </el-select>
      </el-form-item>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开始日期" prop="startDate">
            <el-date-picker
              v-model="contractForm.startDate"
              type="date"
              placeholder="请选择开始日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束日期" prop="endDate">
            <el-date-picker
              v-model="contractForm.endDate"
              type="date"
              placeholder="请选择结束日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="合同金额" prop="amount">
        <el-input-number
          v-model="contractForm.amount"
          :min="0"
          :precision="2"
          :step="1000"
          controls-position="right"
          style="width: 100%"
        />
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-select v-model="contractForm.status" placeholder="请选择状态" class="form-item-width">
          <el-option label="生效中" value="active" />
          <el-option label="已过期" value="expired" />
          <el-option label="已终止" value="terminated" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="contractForm.remark"
          type="textarea"
          placeholder="请输入备注"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveContract" :loading="saving">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import AdvancedTable from '@/components/AdvancedTable.vue'
import * as contractAPI from '@/api/contract'
import * as procurementAPI from '@/api/procurement'

interface Contract {
  id: number
  contractNumber: string
  supplierId: number
  contractName: string
  contractType: 'purchase' | 'service' | 'other'
  startDate: string
  endDate: string
  amount: number
  status: 'active' | 'expired' | 'terminated'
  attachment: string
  remark: string
  createdAt: string
  updatedAt: string
  supplier?: {
    id: number
    name: string
  }
}

interface Supplier {
  id: number
  name: string
}

// 数据状态
const contracts = ref<Contract[]>([])
const suppliers = ref<Supplier[]>([])
const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const editingContract = ref<Contract | null>(null)

// 分页配置
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 筛选参数
const filterParams = reactive({
  supplierId: undefined as number | undefined,
  status: undefined as string | undefined
})

// 合同表单
const contractForm = reactive({
  contractNumber: '',
  supplierId: undefined as number | undefined,
  contractName: '',
  contractType: 'purchase' as 'purchase' | 'service' | 'other',
  startDate: '',
  endDate: '',
  amount: 0,
  status: 'active' as 'active' | 'expired' | 'terminated',
  remark: ''
})

// 表单验证规则
const contractRules = {
  contractNumber: [
    { required: true, message: '请输入合同编号', trigger: 'blur' }
  ],
  supplierId: [
    { required: true, message: '请选择供应商', trigger: 'change' }
  ],
  contractName: [
    { required: true, message: '请输入合同名称', trigger: 'blur' }
  ],
  startDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择结束日期', trigger: 'change' }
  ],
  amount: [
    { required: true, message: '请输入合同金额', trigger: 'blur' }
  ]
}

// 表格列配置
const contractColumns = computed(() => [
  {
    prop: 'contractNumber',
    label: '合同编号',
    width: 150,
    fixed: 'left'
  },
  {
    prop: 'supplier.name',
    label: '供应商',
    width: 150
  },
  {
    prop: 'contractName',
    label: '合同名称',
    width: 200
  },
  {
    prop: 'contractType',
    label: '合同类型',
    width: 100,
    slot: 'contractType'
  },
  {
    prop: 'startDate',
    label: '开始日期',
    width: 120,
    formatter: (value: string) => value ? value.split('T')[0] : ''
  },
  {
    prop: 'endDate',
    label: '结束日期',
    width: 120,
    formatter: (value: string) => value ? value.split('T')[0] : ''
  },
  {
    prop: 'amount',
    label: '合同金额',
    width: 120,
    slot: 'amount'
  },
  {
    prop: 'status',
    label: '状态',
    width: 100,
    slot: 'status'
  },
  {
    prop: 'actions',
    label: '操作',
    width: 150,
    fixed: 'right',
    slot: 'actions'
  }
])

// 分页配置
const paginationConfig = computed(() => ({
  currentPage: pagination.page,
  pageSize: pagination.limit,
  total: pagination.total,
  pageSizes: [10, 20, 50, 100],
  layout: 'total, sizes, prev, pager, next, jumper'
}))

// 加载合同列表
const loadContracts = async () => {
  loading.value = true
  try {
    const params = {
      ...filterParams,
      page: pagination.page,
      limit: pagination.limit
    }
    
    const response = await contractAPI.getContracts(params)
    if (response.success) {
      contracts.value = response.data.list || []
      pagination.total = response.data.pagination?.total || 0
    } else {
      contracts.value = []
      pagination.total = 0
      throw new Error(response.message || '获取合同列表失败')
    }
  } catch (error) {
    ElMessage.error('加载合同列表失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

// 加载供应商列表
const loadSuppliers = async () => {
  try {
    const response = await procurementAPI.getSuppliers({
      page: 1,
      limit: 1000
    })
    if (response.success) {
      suppliers.value = response.data?.list || []
    } else {
      suppliers.value = []
      throw new Error(response.message || '获取供应商列表失败')
    }
  } catch (error) {
    ElMessage.error('加载供应商列表失败: ' + (error as Error).message)
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  editingContract.value = null
  Object.assign(contractForm, {
    contractNumber: '',
    supplierId: undefined,
    contractName: '',
    contractType: 'purchase',
    startDate: '',
    endDate: '',
    amount: 0,
    status: 'active',
    remark: ''
  })
  dialogVisible.value = true
}

// 查看合同
const viewContract = (contract: Contract) => {
  ElMessage.info('查看合同功能待实现')
}

// 编辑合同
const editContract = (contract: Contract) => {
  editingContract.value = contract
  Object.assign(contractForm, { ...contract })
  dialogVisible.value = true
}

// 删除合同
const deleteContract = async (contract: Contract) => {
  try {
    await ElMessageBox.confirm(`确定要删除合同 "${contract.contractNumber}" 吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await contractAPI.deleteContract(contract.id)
    ElMessage.success('合同删除成功')
    loadContracts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除合同失败: ' + (error as Error).message)
    }
  }
}

// 保存合同
const saveContract = async () => {
  saving.value = true
  try {
    if (editingContract.value) {
      // 更新合同
      await contractAPI.updateContract(editingContract.value.id, { ...contractForm })
      ElMessage.success('合同更新成功')
    } else {
      // 创建合同
      await contractAPI.createContract({ ...contractForm })
      ElMessage.success('合同创建成功')
    }
    
    dialogVisible.value = false
    loadContracts()
  } catch (error) {
    ElMessage.error('保存合同失败: ' + (error as Error).message)
  } finally {
    saving.value = false
  }
}

// 重置筛选条件
const resetFilter = () => {
  Object.assign(filterParams, {
    supplierId: undefined,
    status: undefined
  })
  loadContracts()
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pagination.limit = size
  loadContracts()
}

// 处理当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadContracts()
}

// 生命周期
onMounted(() => {
  loadContracts()
  loadSuppliers()
})
</script>

<style scoped>
.contract-management-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-form {
  margin-bottom: 20px;
}

.filter-form .el-form-item {
  margin-right: 20px;
}

.form-item-width {
  width: 200px;
}

</style>